import axios from "axios";
import { getTempPath } from "../../utils";
import path from 'node:path';
import fs from 'node:fs';
import mime from 'mime-types';
import { v4 as uuidv4 } from 'uuid';
import dayjs from 'dayjs';

const tempPath = getTempPath();
const cacheDir = path.join(tempPath, 'cache');
const dowmloadCacheFileName = 'download_records.json'

export async function downloadFileLocal(url, cache = true) {
  if (cache) {
    const cachedFile = getDownloadFileByCache(url);

    if (cachedFile) {
      return cachedFile;
    }
  }

  const tempDir = getTempPath()
  const fileTempPath = path.join(tempDir, 'files', dayjs().format('YYYYMMDD'));

  if (!fs.existsSync(fileTempPath)) {
    fs.mkdirSync(fileTempPath, { recursive: true });
  }

  try {
    // 下载文件并获取响应头
    const response = await axios({
      url,
      method: 'GET',
      responseType: 'stream'
    });

    // 获取文件扩展名
    let ext = path.extname(url);
    if (!ext) {
      const contentType = response.headers['content-type'];
      ext = mime.extension(contentType) ? `.${mime.extension(contentType)}` : '';
    }

    // 生成唯一文件名
    const fileName = `${uuidv4()}${ext}`;
    const filePath = path.join(fileTempPath, fileName);

    // 创建写入流
    const writer = fs.createWriteStream(filePath);

    // 将响应流写入文件
    response.data.pipe(writer);

    return new Promise((resolve, reject) => {
      writer.on('finish', () => {
        // 下载完成后更新缓存记录
        updateCacheRecord(url, filePath, dowmloadCacheFileName);
        
        resolve(filePath);
      });
      writer.on('error', reject);
    });
  } catch (error) {
    throw new Error(`下载文件失败: ${error.message}`);
  }
}

export function getDownloadFileByCache(url) {
  const records = getCacheRecord(dowmloadCacheFileName);

  if (records[url] && fs.existsSync(records[url].content)) {
    return records[url].content;
  }

  return null;
}

export function getCacheRecord(fileName){  
  if (!fs.existsSync(cacheDir)) {
    fs.mkdirSync(cacheDir, { recursive: true });
  }

  const cacheRecordPath = path.join(cacheDir, fileName);

  if (!fs.existsSync(cacheRecordPath)) {
    fs.writeFileSync(cacheRecordPath, JSON.stringify({}));
  }

  return JSON.parse(fs.readFileSync(cacheRecordPath, 'utf8'));
}

export function updateCacheRecord(url, content, fileName) {
  const cacheRecordPath = path.join(cacheDir, fileName);
  const records = getCacheRecord(fileName);

  records[url] = {
    content: (typeof content === 'object' ? JSON.stringify(content) : content),
    timestamp: Date.now()
  };

  fs.writeFileSync(cacheRecordPath, JSON.stringify(records, null, 2));
}

export function getFileSize(filePath) {
  return new Promise((resolve, reject) => {
    fs.stat(filePath, (err, stats) => {
      if (err) {
        reject(err);
      } else {
        resolve(stats.size);
      }
    });
  });
}

export function getPathInfo(fullPath){
	const q = {};
	const [ path, query ] = fullPath.split("?");
	
	try {
		query
			.split("&")
			.forEach((e) => {
				const [k, v] = e.split("=");
				q[k] = decodeURIComponent(v);
			});
	} catch (e) {}

	return {
		path,
		query: q
	}
}

export function generateRandom(length = 6, type = -1, addChars = '') {
  let chars = '';
  switch (type) {
    case 0:
      chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' + addChars;
      break;
    case 1:
      chars = '012345678901234567890123456789';
      break;
    case 2:
      chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + addChars;
      break;
    case 3:
      chars = 'abcdefghijklmnopqrstuvwxyz' + addChars;
      break;
    default:
      chars = 'ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789' + addChars;
      break;
  }

  if (length > 10) {
    chars = type === 1 ? chars.repeat(length) : chars.repeat(5);
  }

  // 模拟 PHP 的 str_shuffle
  const shuffled = chars.split('').sort(() => Math.random() - 0.5).join('');

  return shuffled.substring(0, length);
}